package config

import (
	"fmt"
	"os"

	"gopkg.in/yaml.v2"
)

// Config 系统配置
type Config struct {
	Server   ServerConfig   `yaml:"server"`
	Database DatabaseConfig `yaml:"database"`
	JWT      JWTConfig      `yaml:"jwt"`
}

// ServerConfig 服务器配置
type ServerConfig struct {
	Port string `yaml:"port"`
}

// DatabaseConfig 数据库配置
type DatabaseConfig struct {
	Host     string `yaml:"host"`
	Port     string `yaml:"port"`
	User     string `yaml:"user"`
	Password string `yaml:"password"`
	DBName   string `yaml:"dbname"`
}

// JWTConfig JWT配置
type JWTConfig struct {
	Secret string `yaml:"secret"`
}

// LoadConfig 加载配置
func LoadConfig() *Config {
	// 首先尝试从YAML加载
	config, err := loadFromYAML()
	if err == nil {
		return config
	}

	// 如果YAML加载失败，则从环境变量加载
	return &Config{
		Server: ServerConfig{
			Port: getEnv("SERVER_PORT", "8080"),
		},
		Database: DatabaseConfig{
			Host:     getEnv("DB_HOST", "127.0.0.1"),
			Port:     getEnv("DB_PORT", "3306"),
			User:     getEnv("DB_USER", "root"),
			Password: getEnv("DB_PASSWORD", "password"),
			DBName:   getEnv("DB_NAME", "admin_system"),
		},
		JWT: JWTConfig{
			Secret: getEnv("JWT_SECRET", "your-secret-key"),
		},
	}
}

// loadFromYAML 从YAML文件加载配置
func loadFromYAML() (*Config, error) {
	// 尝试多个可能的配置文件路径
	possiblePaths := []string{
		"config.yaml",               // 当前目录
		"config/config.yaml",        // config子目录
		"server/config/config.yaml", // server/config子目录
	}

	var yamlFile []byte
	var err error
	var readErr error

	for _, path := range possiblePaths {
		yamlFile, readErr = os.ReadFile(path)
		if readErr == nil {
			// 找到并成功读取文件
			fmt.Printf("从路径加载配置: %s\n", path)
			break
		}
	}

	// 如果所有路径都失败
	if readErr != nil {
		return nil, fmt.Errorf("无法找到或读取配置文件: %v", readErr)
	}

	// 解析YAML
	var config Config
	err = yaml.Unmarshal(yamlFile, &config)
	if err != nil {
		return nil, fmt.Errorf("无法解析YAML配置: %v", err)
	}

	return &config, nil
}

// DSN 获取数据库连接字符串
func (c *DatabaseConfig) DSN() string {
	return c.User + ":" + c.Password + "@tcp(" + c.Host + ":" + c.Port + ")/" + c.DBName + "?charset=utf8mb4&parseTime=True&loc=Local"
}

// getEnv 获取环境变量，如果不存在则返回默认值
func getEnv(key, defaultValue string) string {
	if value, exists := os.LookupEnv(key); exists {
		return value
	}
	return defaultValue
}
